package com.briup.client;

import com.briup.entity.Environment;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import java.util.stream.Collectors;

import static com.briup.util.jdbcUtil.getConnection;



/**
 * @Auther: vanse(lc)
 * @Date: 2024/7/12-07-12-17:09
 * @Description：com.briup.env.client
 */
public class Client {
    public void send(List<Environment> list)  {
        Logger logger = Logger.getLogger(Client.class.getName());
        if(list==null){
            logger.info("数据接受有误");
        }
        Connection conn;
        try {
            conn=getConnection();
            conn.setAutoCommit(false);
            int i=0;
            Map<Integer, List<Environment>> collect = list.stream().collect(Collectors.groupingBy(Environment -> Environment.getGather_date().toLocalDateTime().getDayOfMonth()));
            for (List<Environment> value : collect.values()) {
                int day = value.get(0).getGather_date().toLocalDateTime().getDayOfMonth();
                String sql ="insert into environment_copy"+day+" (name, srcId, desId, devId, sersorAddress, count, cmd, status, data, gather_date) values (?,?,?,?,?,?,?,?,?,?)";
                PreparedStatement pstmt=conn.prepareStatement(sql);
                for (Environment e : value) {
                    i++;
                    pstmt.setString(1,e.getName());
                    pstmt.setString(2,e.getSrcId());
                    pstmt.setString(3,e.getDesId());
                    pstmt.setString(4,e.getDevId());
                    pstmt.setString(5,e.getSersorAddress());
                    pstmt.setInt(6,e.getCount());
                    pstmt.setString(7,e.getCmd());
                    pstmt.setInt(8,e.getStatus());
                    pstmt.setFloat(9,e.getData());
                    pstmt.setTimestamp(10,e.getGather_date());
                    pstmt.addBatch();
                    pstmt.executeBatch();
                    if(i%200==0){
                        pstmt.executeBatch();
                        conn.commit();
                        i=0;
                    }
                }
                if (pstmt != null) {
                    pstmt.executeBatch();
                }
                conn.commit();
                if (pstmt != null) {
                    pstmt.close();
                }
            }
            conn.close();
        } catch (Exception ex) {
            throw new RuntimeException(ex);
            }
    }

}
